package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@Controller
//@ResponseBody
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    BookService service;

    //restful的post表示新增
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean result = service.save(book);
        Integer code = result? Code.SAVE_OK : Code.SAVE_ERR;
        String message = result? "保存成功" : "保存失败";
        // {"code" : 20011, "data" : true,"message" : "保存成功"}
        // {"code" : 20010, "data" : false,"message" : "保存失败"}
        return new Result(code,result,message);
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        boolean result = service.updateById(book);
        Integer code = result? Code.UPDATE_OK : Code.UPDATE_ERR;
        String message = result? "修改成功" : "修改失败";
        return new Result(code,result,message);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean result = service.removeById(id);
        Integer code = result? Code.DELETE_OK : Code.DELETE_ERR;
        String message = result? "删除成功" : "删除失败";
        return new Result(code,result,message);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = service.getById(id);
        Integer code = book != null? Code.GET_OK : Code.GET_ERR;
        String message = book != null? "查询单个成功" : "查询单个失败";
        return new Result(code,book,message);
    }

    @GetMapping
    public Result getAll(){
        List<Book> list = service.list();
//        int i = 1/0;
        Integer code = list != null && list.size() != 0? Code.GET_OK : Code.GET_ERR;
        String message = list != null && list.size() != 0? "查询全部成功" : "查询全部失败";
        return new Result(code,list,message);
    }

}
